<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Withdraw extends AdminController{
	public $_validation = null;
	private $_withdrawAmount = 0;
	
	function __construct(){
		parent::__construct();
		$this->load->model('MWithdraw');
		$this->pay_status_css = array(
				'0'=>'label label-sm label-warning',
				'1'=>'label label-sm label-success',
				'-1'=>'label label-sm label-default',
		        '-2'=>'label label-sm label-info',
		        '-3'=>'label label-sm label-danger'
		);
		$this->transfer_status_css = array(
				'0'=>'label label-sm label-danger',
				'1'=>'label label-sm label-success',
				'2'=>'label label-sm label-info'
		);
	}
	
	function index(){
		//$this->output->enable_profiler(TRUE);
		$this->load->library('FormFilter');
		$this->load->helper('formfilter');
		$this->formfilter->addFilter('no', 'where');
		$this->formfilter->addFilter('withdraw.user_id','where');
		$this->formfilter->addFilter('user.account','where');
		$this->formfilter->addFilter('transfer_status','where');
		$this->formfilter->addFilter('withdraw_status','where');
		
		$limit = $this->pagination($this->MWithdraw->getCount());
		//最新一条记录
		$lastItem = $this->MWithdraw->getLast();
		$list = $this->MWithdraw->getList($limit);
		$this->assign('list', $list);
		$this->assign('lastItem', $lastItem);
		$this->layout();
	}
	
	function view($id){
	    if(!$this->p->edit){
	        //权限不足
	        show_error(l('user_has_nopower'));
	    }
		if(!is_numeric($id)){
			show_error(l('id_not_null'));
		}
		$obj = $this->MWithdraw->getOne(Array('id'=>$id));
		if(!$obj){
			errorAndRedirect('未找到定义！');
		}
		//该用户所有曾经充值订单记录
		$this->load->model('MOrder');
		$orders = $this->MOrder->getAll(Array('user_id'=>$obj->user_id));
		//该用户所有曾经提款订单记录
		$withdraws = $this->MWithdraw->getAll(Array('user_id'=>$obj->user_id,'id !='=>$obj->id));
		//当前用户游戏记录列表
		$this->load->library('FormFilter');
		$this->load->helper('formfilter');
		$this->load->model('MGameRecord');
		$limit = $this->pagination($this->MGameRecord->getCount($obj->user_id),'',10);
		$gameRecordList = $this->MGameRecord->getList($limit,$obj->user_id);
		
		$this->load->model('MWithdrawLog');
		$withdrawLogList = $this->MWithdrawLog->getAll(Array('withdraw_id'=>$id));
		$this->load->model('MUserBank');
		$userBankInfo = $this->MUserBank->getOne(array('id'=>$obj->withdraw_bank_id)) ?: $this->MUserBank->createVo();
		$this->assign('orders', $orders);
		$this->assign('withdraws', $withdraws);
		$this->assign('withdraw', $obj);
		$this->assign('withdrawLogList', array_reverse($withdrawLogList));
		$this->assign('userBankInfo', $userBankInfo);
		$this->assign('list', $gameRecordList);
		$this->layout('view');
	}
	
	// 提款弹出框
	function withdrawPopup($id, $update_time){
	    if(!$this->p->edit){
	        //权限不足
	        model_error(l('user_has_nopower'));
	    }
	    if(((int)$id) . '' !== $id){
	        model_error(l('id_or_updated_not_null'));
	    }
	    // 跳转页面
	    $redirectUrl = site_url($this->_thisModule.$this->_thisController.'/view/'.$id);
	    if(!$withdrawInfo = $this->MWithdraw->getOne(array('id'=>(int)$id))){
	        model_error('当前红利信息不存在！');
	    }
	    if ($update_time != $withdrawInfo->update_time) {
	        model_error('操作冲突，请重试！');
	    }
	    $this->load->model('MUserBank');
	    $userBankInfo = $this->MUserBank->getOne(array('id'=>$withdrawInfo->withdraw_bank_id)) ?: $this->MUserBank->createVo();
	    $this->load->library('form_validation');
	    $this->form_validation->set_rules('withdraw_transaction', '通道流水号', 'required|max_length[32]');
	    $this->form_validation->set_rules('note', '备注信息', '');
	    if ($this->form_validation->run()) {
	       //具体操作
	        if ($withdrawInfo->transfer_status != IOSS_Withdraw::TRANSFER_STATE_SUCCESS || $withdrawInfo->withdraw_status != IOSS_Withdraw::WITHDRAW_STATE_NOT_PAID){
	            //提款状态为必须是已从游戏提取、未给用户打款才可以进行打款操作
	            model_error('红利状态不正确');
	        }
	        //修改提款记录状态
	        $time = time();
	        $withdrawInfo->withdraw_status = IOSS_Withdraw::WITHDRAW_STATE_PAID;
	        $withdrawInfo->withdraw_transaction = $this->input->post('withdraw_transaction');
	        $withdrawInfo->withdraw_time = $time;
	        if(!$this->MWithdraw->update($withdrawInfo)){
	            model_error('修改红利状态失败');
	        }
	        //操作日志添加记录
	        $this->load->model('MWithdrawLog');
	        $newLog = new stdClass();
	        $newLog->withdraw_id = $withdrawInfo->id;
	        $newLog->withdraw_status = $withdrawInfo->withdraw_status;
	        $newLog->transfer_status = $withdrawInfo->transfer_status;
	        $newLog->admin_id = $this->_user->id;
	        $newLog->admin_account = $this->_user->account;
	        $newLog->admin_name = $this->_user->name;
	        $newLog->note = '【客服操作】'.$this->input->post('note');
	        $newLog->create_time = $time;
	        $this->MWithdrawLog->add($newLog);
	        model_success('红利发放成功');
	    }
	    $this->assign('thisControllerName', '红利发放');
	    $this->assign('withdrawInfo', $withdrawInfo);
	    $this->assign('userBankInfo', $userBankInfo);
	    $this->layout_modal('withdraw-popup');
	}
	
	// 提款拒绝弹出框
	function withdrawRefusePopup($id, $update_time){
	    if(!$this->p->edit){
	        //权限不足
	        model_error(l('user_has_nopower'));
	    }
	    if(((int)$id) . '' !== $id){
	        model_error(l('id_or_updated_not_null'));
	    }
	    // 跳转页面
	    $redirectUrl = site_url($this->_thisModule.$this->_thisController.'/view/'.$id);
	    if(!$withdrawInfo = $this->MWithdraw->getOne(array('id'=>(int)$id))){
	        model_error('当前红利信息不存在！');
	    }
	    $this->_withdrawAmount = $withdrawInfo->amount;
	    if ($update_time != $withdrawInfo->update_time) {
	        model_error('操作冲突，请重试！');
	    }
	    $this->load->library('form_validation');
	    $this->form_validation->set_rules('refuse_type', '拒绝方式', 'required|integer');
	    $this->form_validation->set_rules('set_amount', '设定返回到平台数量', 'greater_than[0]|callback__checkSetAmount');
	    $this->form_validation->set_rules('note', '备注信息', 'required');
	    if ($this->form_validation->run()) {
	        //具体操作
	        if ($withdrawInfo->withdraw_status != IOSS_Withdraw::WITHDRAW_STATE_NOT_PAID){
	            //提款状态为必须是未给用户打款才可以进行打款操作
	            model_error('红利状态不正确');
	        }
	        $setAmount = $this->input->post('set_amount');
	        if(isset($setAmount) && $setAmount>$withdrawInfo->amount){
	            model_error('设定返回到平台操作的数量不能大于此次红利数量！');
	        }
	        //修改提款记录状态
	        $time = time();
	        $refuseType = $this->input->post('refuse_type');
	        if($refuseType == '-2'){   //拒绝并退回充值到游戏
	            $withdrawInfo->withdraw_status = IOSS_Withdraw::WITHDRAW_STATE_REFUSED_BACKTOGAME;
	        }else{     //直接拒绝提款不退回游戏
	            $withdrawInfo->withdraw_status = IOSS_Withdraw::WITHDRAW_STATE_REFUSED;
	        }
	        
	        if(!$this->MWithdraw->update($withdrawInfo)){
	            model_error('修改红利状态失败');
	        }
	        //如果有设定的金额，将充值到游戏中
	        if($setAmount){
	            //调用充值接口给游戏充值----------------------------------------------
	            $user = IOSS_User::getById($withdrawInfo->user_id);
	            $billno = date('ymdHis') . rand(1000,9999);
	            // 预转账
	            if(!IOSS_AGApi::agin_prepare_transfer_credit($user->account, $user->game_key, $billno, 'IN', $setAmount, $prepare_error_message)){
	                model_error('设定返回平台操作数量预操作失败！'.$prepare_error_message["Message"]); // 预转账失败
	            }
	            // 转账确认
	            if (!IOSS_AGApi::agin_confirm_transfer_credit($user->account, $user->game_key, $billno, 'IN', $setAmount, $confirm_error_message)){
	                if ($confirm_error_message['Type'] === 'network_error') {
	                    if (!IOSS_AGApi::agin_query_transfer_status($billno, $query_error_message)) {
	                        model_error('设定返回平台操作数量状态确认未成功！'.$query_error_message["Message"]); 
	                    }
	                }else{
	                    model_error('设定返回平台操作数量操作失败！'.$confirm_error_message['Message']);
	                }
	            }
	            //--------------------------------------------------------------
	        }
	        //提款操作日志添加记录
	        $this->load->model('MWithdrawLog');
	        $newLog = new stdClass();
	        $newLog->withdraw_id = $withdrawInfo->id;
	        $newLog->withdraw_status = $withdrawInfo->withdraw_status;
	        $newLog->transfer_status = $withdrawInfo->transfer_status;
	        $newLog->admin_id = $this->_user->id;
	        $newLog->admin_account = $this->_user->account;
	        $newLog->admin_name = $this->_user->name;
	        $newLog->note = '【客服操作】'.$this->input->post('note');
	        $newLog->create_time = $time;
	        $this->MWithdrawLog->add($newLog);
	        
	        //后台变更操作日志添加记录
	        $this->load->model('MHandleRecord');
	        $handleRecord = new stdClass();
	        $handleRecord->withdraw_no = $withdrawInfo->no;
	        $handleRecord->user_id = $withdrawInfo->user_id;
	        $handleRecord->admin_id = $this->_user->id;
	        $handleRecord->admin_name = $this->_user->name;
	        $handleRecord->handle_type = $setAmount?1:0;   //有设定充值金额为1否则为0
	        $handleRecord->withdraw_amount = $withdrawInfo->amount;
	        $handleRecord->ingame_amount = NULL;
	        $handleRecord->handle_amount = $setAmount?$setAmount:NULL;
	        $handleRecord->remark = $setAmount?'红利申请'.$withdrawInfo->amount.'被驳回,退回平台'.$setAmount:'红利申请'.$withdrawInfo->amount.'被驳回';
	        $handleRecord->create_time = $time;
	        $handleRecord->update_time = $time;
	        $this->MHandleRecord->add($handleRecord);
	        model_success('红利申请拒绝操作成功');
	    }
	    $this->assign('thisControllerName', '红利申请驳回');
	    $this->assign('withdrawInfo', $withdrawInfo);
	    $this->layout_modal('withdraw-refuse-popup');
	}
	
	/**
	 * ajax请求最新的记录id
	 */
	public function pollingWithdrawLastId(){
	    $lastItem = $this->MWithdraw->getLast();
	    $retObj = new stdClass();
	    $retObj->lastId = $lastItem->id;
	    echo json_encode($retObj);
	}
	
	/**
	 * 检查设定返回充值到游戏的金额
	 * @param string $amount 传来表单金额
	 */
	function _checkSetAmount($amount){
	    if($amount > $this->_withdrawAmount){
	        $this->form_validation->set_message('_checkSetAmount', '设定返回到平台操作的数量不能大于此次红利数量'.$this->_withdrawAmount);
	        return false;
	    }
	    return true;
	}
}